package cn.texous.web.parsing.book.strategy.search.fiction;

import cn.texous.util.commons.constant.Result;
import cn.texous.util.commons.util.GsonUtils;
import cn.texous.web.parsing.book.model.bo.publisher.AnaBookAddOrUpdateBO;
import cn.texous.web.parsing.book.model.dto.AnaSearchBookDTO;
import cn.texous.web.parsing.book.model.parser.origin.AnaOriginParser;
import cn.texous.web.parsing.book.model.resp.AnaSearchBookResp;
import cn.texous.web.parsing.book.publisher.fiction.AnaFictionSubscribe;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * insert description here
 *
 * @author Showa.L
 * @since 2019/7/26 13:08
 */
@Slf4j
@Component(FictionContentProcessor.FCP)
public class FictionContentProcessor extends AbstractContentProcessor<AnaSearchBookResp> {

    /**
     * bean name
     */
    public static final String FCP = "fictionContentProcessor";

    @Override
    public AnaSearchBookResp process(Result<String> content, AnaOriginParser originParser, Map<String, Object> otherInfo) {
        // 获取字段解析器
        AnaSearchBookResp resp = null;
        if (validateResult(content)) {
            resp = GsonUtils.fromJson(
                    content.getData(), AnaSearchBookResp.class);
            // 存储结果
            fictionAddOrUpdatePublish(resp.getBooks(), originParser.getOrigin());
        }
        // 返回结果
        return resp;
    }

    private void fictionAddOrUpdatePublish(List<AnaSearchBookDTO> anaFictions, String origin) {
        try {
            AnaBookAddOrUpdateBO bo = new AnaBookAddOrUpdateBO();
            bo.setOrigin(origin);
            bo.setBooks(anaFictions);
            anaPublisher.publisher(bo, AnaFictionSubscribe.TOPIC);
        } catch (Exception e) {
            log.error("书籍更新发布失败", e);
        }
    }

}
